<?php
namespace app\common\library\mstching;
use app\common\model\WebSet;

/*
 * 易联云打印机驱动模块
 * 测试机型号：K4-WH
*/
class YiLian
{
	private $baseurl = 'https://open-api.10ss.net/';//接口路径
	private $appid = '';		
	private $appsecret = '';
	private $access_token = '';
	
	/**
	 * 构造函数
	 */
	public function __construct()
	{
		$values = WebSet::getItem('printer');
		$this->appid = $values['yilian']['app_key'];
		$this->appsecret = $values['yilian']['app_secret'];
		$this->access_token = $values['yilian']['access_token'];
		
	}
	
	/**
	* 打印订单接口
	* $machine_code 打印机终端号
	* $n 打印份数
	*/
	public function printMsg($data ,$machine_code,$n=2)
	{
		$content = $this->make_order_templet($data,$n);//获取打印模板
		$params = $this->params();
		$params['machine_code'] = $machine_code;//打印机终端号
		$params['origin_id'] = $data['order_id'];//订单编号
		$params['content'] = $content;//打印内容
        $res = json_decode($this->http_post_json($params,'print/index'),true);
		if($res['error']==0){
			return $res['body'];//返回数据 {"id":"订单号","origin_id":""}
		}
		return false;
	}
	
	/**
	* 授权绑定打印机
	*/
	public function printerAdd($data)
	{
		$params = $this->params();
		$params['print_name'] = $data['printer_name'];//自定义打印机名称(可填)
		$params['machine_code'] = $data['uuid'];//打印机终端号
		$params['msign'] = $data['key'];//打印机终端密钥
		$params['phone'] = $data['phone'];//手机卡号码(可填)
        $res = json_decode($this->http_post_json($params,'printer/addprinter'),true);
		if($res['error']==0){
			return true;
		}
		return false;
	}
	
	/**
	* 删除授权绑定的打印机
	*/
	public function printerDel($machine_code){
		$params = $this->params();
		$params['machine_code'] = $machine_code;//打印机编号
		$res = json_decode($this->http_post_json($params,'printer/deleteprinter'),true);
		if($res['error']==0){
			return true;
		}
		return false;
	}
	
	/**
	* 获取打印机状态接口 
	*/
	public function queryPrinterStatus($machine_code){
		$params = $this->params();
		$params['machine_code'] = $machine_code;//打印机编号
		$res = json_decode($this->http_post_json($params,'printer/getprintstatus'),true);
		if($res['error']==0){
			$msg = '离线';
			if($res['body']['state']==1){
				$msg = '正常';
			}
			if($res['body']['state']==2){
				$msg = '缺纸';
			}
			return $msg;
		}
		return false;
	}

	/**
	* 获取Token
	*/
	public function getToken($appid,$appsecret)
    {
		$this->appid = $appid;
		$this->appsecret = $appsecret;
        $time = time();
        $params = [
            'client_id' => $this->appid,
            'timestamp' => $time,
            'sign' => $this->getSign($time),
            'id' => $this->uuid4(),
            'scope' => 'all'
        ];
        $params['grant_type'] = 'client_credentials';
        $res = json_decode($this->http_post_json($params,'oauth/oauth'),true);
		if($res['error']==0){
			return $res['body']['access_token'];
		}
		return '';
    }
	
	/**
	* 公共参数
	*/
	private function params(){
		$time = time();         //请求时间
		return $params = [
			'client_id' => $this->appid,
			'access_token' => $this->access_token,
            'timestamp' => $time,
            'sign' => $this->getSign($time),
            'id' => $this->uuid4(),
		];
	}
	
	/**
	* 生成签名
	*/
	private function getSign($timestamp)
    {
        return md5($this->appid . $timestamp . $this->appsecret);
    }

	/**
	* 生成uuid4
	*/
    private function uuid4(){
        mt_srand((double)microtime() * 10000);
        $charid = strtolower(md5(uniqid(rand(), true)));
        $hyphen = '-';
        $uuidV4 =
            substr($charid, 0, 8) . $hyphen .
            substr($charid, 8, 4) . $hyphen .
            substr($charid, 12, 4) . $hyphen .
            substr($charid, 16, 4) . $hyphen .
            substr($charid, 20, 12);
        return $uuidV4;
    }
	
	
	//发送post请求
	/**
	 * PHP发送Json对象数据
	 * @return string
	 */
	private function http_post_json($data,$url)
	{
		$url = $this->baseurl . $url;
		$data = http_build_query($data);
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检测
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Expect:'
        )); // 解决数据包大不能提交
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($ch, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循
        curl_setopt($ch, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
		$response = curl_exec($ch);
		$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		curl_close($ch);
		return $response;
	}

	/**
	 * 制作订单模板
	 * $data 订单数据
	 * $打印份数
	 * 58mm的机器,一行打印16个汉字,32个字母;
	 */
	private function make_order_templet($data,$n)
	{
		$content = '<MN>'.$n.'</MN>';
		if($data['table_id']>10000){
			$content .= '<FS><center># '.$data['table']['table_name'].' #</center></FS>';
		}
		if($data['table_id']==1){
			$content .= '<FS><center># 堂食'.$data['row_no'].'号 #</center></FS>';
		}
		if($data['table_id']==2){
			$content .= '<FS><center># 自取'.$data['row_no'].'号 #</center></FS>';
			$content .= '到店时间:'.$data['arrive_time'].'\n';
		}
		if($data['table_id']==3){
			$content .= '<FS><center># 外卖'.$data['row_no'].'号 #</center></FS>';
		}
		$content .= str_repeat('-', 32);
		$content .= '<center>'.$data['shop']['shop_name'].'</center>';
		if($data['transaction_id']){
			$content .= '<center>-- 微信支付 --</center>';
		}else{
			$content .= '<center>-- 余额支付 --</center>';
		}
		
		$content .= '支付时间:'.date("Y-m-d H:i:s",$data['pay_time']).'\n';
		$content .= str_repeat('-', 32);
		$content .= '名称             单价 数量 金额 \n';//16+6+4+6
		//循环拼接打印模板
		for ($i = 0; $i < sizeof($data['goods']); $i++) {
				$goods_attr = '';
				if($data['goods'][$i]['goods_attr']){
					$goods_attr = ':'+$data['goods'][$i]['goods_attr'];
				}
				$goods_name = $data['goods'][$i]['goods_name'].$goods_attr;//产品名字
				$goods_price = $data['goods'][$i]['goods_price'];	//产品单价
				$total_num = $data['goods'][$i]['total_num'];	//产品数量
				$total_price = $data['goods'][$i]['total_price'];//产品总价格
				
				//设置名称字符长度
				$lan = mb_strlen($goods_name,'utf-8')*2;//一个汉字2个字符长度
				for($n=$lan;$n<16;$n++){
					$goods_name .= ' ';
				}
				//设置单价字符长度
				$lan = mb_strlen($goods_price,'utf-8');
				for($n=$lan;$n<6;$n++){
					$goods_price .= ' ';
				}
				//设置单价字符长度
				$lan = mb_strlen($total_num,'utf-8');
				for($n=$lan;$n<4;$n++){
					$total_num .= ' ';
				}
				//设置单价字符长度
				$lan = mb_strlen($total_price,'utf-8');
				for($n=$lan;$n<6;$n++){
					$total_price .= ' ';
				}
				$content .= $goods_name.$goods_price.$total_num.$total_price.'\n';
		}
		$content .= str_repeat('-', 32);		
		$content .= '商品数量：'.$i.'\n';
		$content .= '商品金额：￥'.$data['total_price'].'元\n';
		if($data['table_id']==3){
			$content .= '配送费用：￥'.$data['express_price'].'元\n';
		}
		if($data['table_id']==2 OR $data['table_id']==3){
			$content .= '餐盒费用：￥'.$data['pack_price'].'元\n';
		}
		if($data['table_id']>10000){
			$content .= '餐具调料：￥'.$data['ware_price'].'元\n';
		}
		$content .= '优惠金额：￥'.$data['activity_price'].'元\n';
		$content .= '实付金额：￥'.$data['pay_price'].'元\n';
		if($data['flavor']){
			$content .= '口味要求：￥'.$data['flavor'].'元\n';
		}
		if($data['message']){
			$content .= '顾客留言：￥'.$data['message'].'元\n';
		}
		if($data['table_id']>10000){
			$content .= '<FS><center># '.$data['table']['table_name'].' # 完</center></FS>';
		}
		if($data['table_id']==1){
			$content .= '<FS><center># 堂食'.$data['row_no'].'号 # 完</center></FS>';
		}
		if($data['table_id']==2){
			$content .= '<FS><center># 自取'.$data['row_no'].'号 # 完</center></FS>';
		}
		if($data['table_id']==3){
			$content .= '<FS><center># 外卖'.$data['row_no'].'号 # 完</center></FS>';
		}
		$content .= '\n';
		return $content;
	}
}